package my.ts.code;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Hashtable;

import my.ts.code.listener.ConfirmListener;
import my.ts.code.objects.PicInfo;
import my.ts.code.viewgroup.CustomViewGroupGallery;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;

public class ShowPic extends BaseActivity implements ConfirmListener {
	private TextView tv;
	private int receicePos, receiveAmount, currentItem, numberItem;
	private HorizontalScrollView hsv;
	private TableRow tar;
	private float WidthOfScreen, x1;
	private ArrayList<String> listImg = new ArrayList<String>();
	private ArrayList<String> listSMSCode = new ArrayList<String>();
	// ,
	// listDownload = new ArrayList<String>();
	private ArrayList<PicInfo> listPic = new ArrayList<PicInfo>();
	private boolean[] Downloaded;
	private boolean dialogErrorShowed = false, end = false;
	private Button Download;
	// private String addUrl = "";
	// private Dialog dialog;
	private Context context;
	private Hashtable<Integer, Bitmap> ImageHashtable = new Hashtable<Integer, Bitmap>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.show_pic);
		context = this;
		setCListener(this);
		Bundle receiveBundle = this.getIntent().getExtras();

		receicePos = receiveBundle.getInt("post");
		currentItem = receicePos;
		receiveAmount = receiveBundle.getInt("amount");
		numberItem = receiveAmount;
		listImg = receiveBundle.getStringArrayList("list");
		listSMSCode = receiveBundle.getStringArrayList("sms");

		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		WidthOfScreen = display.getWidth();

		// listDownload = receiveBundle.getStringArrayList("download");
		tv = (TextView) findViewById(R.id.tv_showpic);
		tv.setText((receicePos + 1) + "/" + receiveAmount);
		tar = (TableRow) findViewById(R.id.content);

		Download = (Button) findViewById(R.id.download);
		Download.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialogSelectSms(
						context,
						ShowPic.this,
						"Tùy chọn",
						"Bạn có đồng ý nhắn tin để $$$ ảnh",
						" ảnh",
						Config.IMAGE_SYNTAX.getSyntax()
								+ listSMSCode.get(currentItem),
						Config.IMAGE_SYNTAX.getNumber());
			}
		});
		// Download.setVisibility(View.GONE);

		hsv = (HorizontalScrollView) findViewById(R.id.slide_bar);
		hsv.setVerticalScrollBarEnabled(false);
		hsv.setHorizontalScrollBarEnabled(false);

		// addUrl = HomePage.addUrl;
		init();

		setDataAtFirstTime();

		hsv.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent e) {
				// TODO Auto-generated method stub
				float x2 = 0, x3 = 0;
				int width = hsv.getMeasuredWidth();
				int border = width / 3;
				switch (e.getAction()) {
				case MotionEvent.ACTION_DOWN: {
					x1 = e.getX();
					return false;
				}
				case MotionEvent.ACTION_UP: {
					x2 = e.getX();
					int moved = (int) (x1 - x2);
					if (moved >= border && currentItem < numberItem - 1) {
						currentItem += 1;
						tv.setText((currentItem + 1) + "/" + receiveAmount);
						setData(currentItem);
						hsv.smoothScrollTo((int) WidthOfScreen * (currentItem),
								0);
					} else if (moved <= -border && currentItem > 0) {
						currentItem -= 1;
						tv.setText((currentItem + 1) + "/" + receiveAmount);
						setData(currentItem);
						hsv.smoothScrollTo((int) WidthOfScreen * (currentItem),
								0);
					} else if ((moved > -border) && (moved < border)) {
						hsv.smoothScrollTo((int) WidthOfScreen * (currentItem),
								0);
					}
					return true;
				}
				case MotionEvent.ACTION_MOVE: {
					return false;
				}
				}
				return true;
			}
		});

	}

	/*
	 * *****************************************************************************************
	 */

	@Override
	public void onPause() {
		end = true;
		super.onPause();
	}

	protected void init() {
		Downloaded = new boolean[numberItem];
		for (int i = 0; i < numberItem; i++) {
			PicInfo pic = new PicInfo(i, "", "", "", "", "", "",
					listImg.get(i), null);
			// new picInfo(i, listImg.get(i), null);
			listPic.add(pic);
			tar.addView(getView(pic, i));
			Downloaded[i] = false;
		}
	}

	/*
	 * *****************************************************************************************
	 */
	protected void setDataAtFirstTime() {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int pos = msg.what;
				if (end == false) {
					if (pos == -3) {
						// if (listDownload.get(currentItem) != null)
						// Download.setVisibility(View.VISIBLE);
						// else
						// Download.setVisibility(View.GONE);
					} else if (pos == -1) {

						System.out.println("RECEIVEPOS=" + receicePos);
						hsv.scrollTo((int) WidthOfScreen * (receicePos), 0);
					} else if (pos >= 0) {
						Bitmap d = (Bitmap) msg.obj;
						ImageView img = (ImageView) findViewById(pos);
						img.setImageBitmap(d);
						Downloaded[pos] = true;
						ImageHashtable.put(pos, d);
					} else if (pos == -2) {
						if (dialogErrorShowed == false && end == false) {
							dialogErrorShowed = true;
							AlertDialog.Builder builder = new AlertDialog.Builder(
									ShowPic.this);
							builder.setTitle("Thông báo");
							builder.setMessage("Kiểm tra lại kết nối mạng hoặc ảnh không tồn tại.");
							builder.setPositiveButton("Đóng cửa sổ",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialogErrorShowed = false;
										}
									});
							builder.show();
						}
					}
				}
				super.handleMessage(msg);
			}
		};

		Thread t = new Thread() {
			@Override
			public void run() {
				Bitmap d = getImage(listImg.get(receicePos));
				if (d != null) {
					Message msgD = handler.obtainMessage(-3);
					handler.sendMessage(msgD);

					Message msg = handler.obtainMessage(receicePos, d);
					handler.sendMessage(msg);
				} else {
					Message msg = handler.obtainMessage(-2);
					handler.sendMessage(msg);
				}
				Message msg0 = handler.obtainMessage(-1);
				handler.sendMessage(msg0);
			}
		};
		t.start();
	}

	/*
	 * ***********************************Method*********************************
	 */
	protected void setData(final int index) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int pos = msg.what;
				if (end == false) {
					if (pos == -3) {
						// if (listDownload.get(currentItem) != null)
						// Download.setVisibility(View.VISIBLE);
						// else
						// Download.setVisibility(View.GONE);

					}

					if (pos >= 0) {
						Bitmap bm = (Bitmap) msg.obj;
						ImageView img = (ImageView) findViewById(pos);
						img.setImageBitmap(bm);
						Downloaded[index] = true;
						ImageHashtable.put(pos, bm);
					}
					if (pos == -2) {
						if (dialogErrorShowed == false) {
							dialogErrorShowed = true;

							AlertDialog.Builder builder = new AlertDialog.Builder(
									ShowPic.this);
							builder.setTitle("Thông báo");
							builder.setMessage("Kiểm tra lại kết nối mạng");
							builder.setPositiveButton("Đóng cửa sổ",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialogErrorShowed = false;
										}
									});
							builder.show();
						}
					}
				}
				super.handleMessage(msg);
			}
		};
		if (Downloaded[index] == true) {
			Log.i("tag", "msg downloaded at = " + Downloaded[index]);
		} else {
			Thread t = new Thread() {
				@Override
				public void run() {
					Bitmap d = getImage(listImg.get(index));
					if (d != null) {
						Message msgD = handler.obtainMessage(-3);
						handler.sendMessage(msgD);

						Message msg = handler.obtainMessage(index, d);
						handler.sendMessage(msg);
					} else {
						Message msg = handler.obtainMessage(-2);
						handler.sendMessage(msg);
					}
				}
			};
			t.start();
		}
	}

	protected Bitmap getImage(String link) {
		URLConnection url;
		Bitmap bm = null;
		try {
			String srcName = link;
			url = new URL(link).openConnection();
			url.setConnectTimeout(3000);
			url.setReadTimeout(5000);
			InputStream is = url.getInputStream();
			bm = BitmapFactory.decodeStream(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bm;
	}

	public View getView(PicInfo o, int index) {
		View paperView = null;
		if (paperView == null) {
			paperView = new CustomViewGroupGallery(getBaseContext());
		}
		if (o != null) {
			int id = o.getPicIndex();
			ImageView i = ((CustomViewGroupGallery) paperView).img;
			i.setId(index);
		}
		return paperView;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			end = true;
			if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
				finish();
			}
		}
		return false;
	}

	@Override
	public void onResume() {
		end = false;
		super.onResume();
	}

	@Override
	public void confirmListener(boolean done) {
		// TODO Auto-generated method stub

	}

}
